//
//  IndexViewController.m
//  Lmm_IOS
//
//  Created by 张哲炜 on 2018/9/14.
//  Copyright © 2018年 lmm. All rights reserved.
//

#import "IndexViewController.h"

@interface IndexViewController (){
    
    NSMutableArray *activityModelArray;
    NSMutableArray *sliderModelArray;
    SDCycleScrollView *cycleScrollView;
    UITableView* tableView ;
    int page;
    UIButton *button;

    UIRefreshControl * refreshControl;
    NSMutableDictionary *cellHeightsDictionary;
    
    
    NSTimer *timer;
    
    NSArray* selectedArray;
    
    NSMutableArray *activityArray;
    
}

@end

@implementation IndexViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
   
    page = 1;
   
    UIView *navigationBar = UIView.new;
    navigationBar.backgroundColor = MAIN_COLOR;
    [self.view addSubview:navigationBar];
    
    UIView *rootView = self.view;
    
    int height = NAVIGATION_BAR_HEIGHT;
    int titleLabelOffset = 20;
    if (DEVICE_IS_IPHONEX) {
        height = NAVIGATION_BAR_X_HEIGHT;
        titleLabelOffset = 40;
    }
    
    [navigationBar makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(rootView.top).offset(0);
        make.left.equalTo(rootView.left).offset(0);
        make.right.equalTo(rootView.right).offset(0);
        make.height.equalTo(height);
    }];
    
    UILabel *titleLabel = UILabel.new;
    titleLabel.font = [UIFont systemFontOfSize:20.0];
    titleLabel.text = @"零买买";
    titleLabel.textColor = [UIColor whiteColor];
    [navigationBar addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navigationBar);
        make.top.equalTo(navigationBar.top).offset(titleLabelOffset);
        make.bottom.equalTo(navigationBar.bottom).offset(0);
    }];
    
    
    tableView=[[UITableView alloc] init];
    //设置行cell高（默认44px）
    //[tableView setRowHeight:300];
    //设置分割线颜色
    //[tableView setSeparatorColor:[UIColor grayColor]];
    tableView.showsVerticalScrollIndicator = YES;
    //tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    //设置分割线风格
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    // 设置数据源代理，必须实现协议UITableViewDataSource中的相关方法
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:self->tableView];
    
    [tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(navigationBar.bottom);
        make.left.equalTo(rootView.left);
        make.right.equalTo(rootView.right);
        make.bottom.equalTo(rootView.bottom).offset(0);
    }];
    
    
    // UIRefreshControl下拉刷新功能的实现
    refreshControl = [[UIRefreshControl alloc] init];
    refreshControl.tintColor = [UIColor redColor];
    refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
    [refreshControl addTarget:self action:@selector(refreshControlAction) forControlEvents:UIControlEventValueChanged];
    [tableView addSubview:refreshControl];
    
    
    cycleScrollView = [ SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 64, MAIN_SCREEN_WIDTH, MAIN_SCREEN_WIDTH/4) delegate:self placeholderImage:nil];
    //cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    // 设置pageControl居右，默认居中
    cycleScrollView.autoScrollTimeInterval = 3;// 自定义轮播时间间隔

    [tableView setTableHeaderView:cycleScrollView];
    
    [self.view addSubview:tableView];
    

//    // 解决上拉加载更多抖动问题
//    self->cellHeightsDictionary = @{}.mutableCopy;
//    self->tableView.rowHeight = UITableViewAutomaticDimension;
//
   
    [self getActivityIndex];
 
    
    self->timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(refreshTime) userInfo:nil repeats:YES];
    
    //解决tableView滑动时tableView暂停的问题
    [[NSRunLoop currentRunLoop] addTimer:self->timer forMode:NSRunLoopCommonModes];
    }


- (void) refreshTime {

    if ([self->activityModelArray count] == 0) {
        return;
    }
//可见的cell的row数
    NSArray *indexPathsForVisibleRows = [self->tableView indexPathsForVisibleRows];

    for ( NSIndexPath *indexPath in indexPathsForVisibleRows ) {
        ActivityTableViewCell *cell = (ActivityTableViewCell *)[self->tableView  cellForRowAtIndexPath:indexPath];
      
            [cell refreshTime];
    }
    
}



-(void)getActivityIndex{
    self->page = 1;
  
    [HttpHelper request:@"activity/index" :@"GET" :nil successBlock:^(NSDictionary *responseDic) {
        
        self->activityModelArray = [ActivityModel mj_objectArrayWithKeyValuesArray:responseDic[@"data"][@"list"]];
        
        //self->activityArray = responseDic[@"data"][@"list"];
        //NSLog(@"%@",  self->activityArray);
        //NSLog(@"%@",self->activityModelArray);
        
        self->sliderModelArray = [SliderModel mj_objectArrayWithKeyValuesArray:responseDic[@"data"][@"slider"]];
        
        NSMutableArray * sliderImgUrlList = NSMutableArray.new;
        
        for (SliderModel* slider in self->sliderModelArray) {
            [sliderImgUrlList addObject:slider.img_url];
        }
        self->cycleScrollView.imageURLStringsGroup = sliderImgUrlList;
        //再下来加载时不会导致已经加载的数据会再刷新
       self->page++;
       
        //很重要这一步，重新加载数据
       [self->tableView reloadData];
       
        [self->refreshControl endRefreshing];

    } failureBlock:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    
}



-(void)getActivityList {
    
    NSString *path = @"activity/list" ;
    NSString *method = @"GET";
    NSMutableDictionary *params = NSMutableDictionary.new;
    [params setValue:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
                                  
    [HttpHelper request:path :method :params successBlock:^(NSDictionary *responseDic) {
        
        NSMutableArray *activityListModelArray = [ActivityModel mj_objectArrayWithKeyValuesArray:responseDic[@"data"]];
        
        //将activityListModelArray的元素添加到activityModelArray
        [self->activityModelArray addObjectsFromArray: activityListModelArray];
        
        self->page++;

        [self->tableView reloadData];

    } failureBlock:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    
}


// 提供tableView中的分区中的数据的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self->activityModelArray count];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return MAIN_SCREEN_WIDTH / 2 + 84;
}


// 返回每行的单元格,提供 tableView 中显示的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"ActivityTableViewCell";
    
    // 根据cellID从可重用表格行的队列中取出可重用的一个表格行UITableViewCell对象
     ActivityTableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    // 如果取出的表格行为nil
    if (tableViewCell == nil) {
            //创建一个UITableViewCell对象，并绑定到cellID
            tableViewCell = [[ActivityTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [tableViewCell setSelectionStyle:UITableViewCellSelectionStyleNone];

        }
    //根据indexPath.row(即cell的顺序)取出activityModelArray的元素
      ActivityModel *activityModel = [self->activityModelArray objectAtIndex:indexPath.row];
    //NSDictionary *activity = [self->activityArray objectAtIndex:indexPath.row];
    
    //将activityModel的数据填入tableViewCell
      [tableViewCell setActivityModel:activityModel];
  //  [tableViewCell setActivity:activity];
    
    
        return tableViewCell;
    
}


////轮播图中的图片顺序数
//- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
//
//    NSLog(@"%ld",index);
//}

//下拉加载的tableView实现方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
        //NSLog(@"scrollView.contentOffset.y==%f",  scrollView.contentOffset.y );
        //NSLog(@"scrollView.contentSize.height ==%f",  scrollView.contentSize.height  );
        //NSLog(@"scrollView.frame.size.height==%f",  scrollView.frame.size.height );
    if(scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.frame.size.height) {
        
        [self getActivityList];
    }
}

-(void)refreshControlAction{
    
    if (self->refreshControl.refreshing) {
        refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"加载中..."];
        
        //self->page = 1;
        
        [self getActivityIndex];
        
    }
}

//给cell预设高度，最好接近其真实高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 300;
    
}



//轮播图点击事件
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    //NSLog(@"%d",index);
    SliderModel *sliderModel = [self->sliderModelArray objectAtIndex:index];
    
    ArticleViewController *articleViewController = ArticleViewController.new;
    articleViewController.id =sliderModel.id;
    
    articleViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:articleViewController animated:YES];
    
}

//// 解决上拉加载更多抖动问题 save height
//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    [self->cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath];
//}
//
//// 解决上拉加载更多抖动问题 give exact height value
//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSNumber *height = [self->cellHeightsDictionary objectForKey:indexPath];
//    if (height) return height.doubleValue;
//    return UITableViewAutomaticDimension;
//}
//


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
          ActivityModel *activityModel = [self->activityModelArray objectAtIndex:indexPath.row];
    
    //取出当前点击的cell
        ActivityTableViewCell *cell = (ActivityTableViewCell *)[self->tableView  cellForRowAtIndexPath:indexPath];
    
  
    NSString *key = [NSString stringWithFormat:@"is_read_activity_id_%d", activityModel.id ];
    [[PINCache sharedCache] setObject:@"1" forKey:key];
    //设置cell标题已读
      [cell setTltleIsReadColor];
    
    
    
    ActivityDetailViewController* activityDetailView = [[ActivityDetailViewController alloc]init];
    activityDetailView.id = activityModel.id;
    //[activityDetailView setId:activityModel.id];
    
    activityDetailView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:activityDetailView animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



@end
